//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from 'react';
import type { NodeProps } from "reactflow";
import LocalNodeWrap from '../LocalNodeWrap';
import type { NodeData } from '../types';
import type { DnsRecord } from "@/api/tencloud/dnspod";
import { listRecord } from "@/api/tencloud/dnspod";
import { get_source, type TenCloudSourceInfo, type UserDataSourceInfo } from '@/api/user_dataview';
import type { ColumnsType } from 'antd/lib/table';
import { Button, Table } from "antd";
import { ReloadOutlined } from '@ant-design/icons';

const TenCloudDnsRecordListNode = (props: NodeProps<NodeData>) => {

    const [recordList, setRecordList] = useState<DnsRecord[]>([]);
    const [dataSource, setDataSource] = useState<UserDataSourceInfo | undefined>(undefined);

    const loadDataSource = async () => {
        const res = await get_source(props.data.dataSourceId ?? "");
        setDataSource(res);
    };

    const loadRecordList = async () => {
        if (dataSource == undefined) {
            return;
        }
        const sourceInfo = JSON.parse(dataSource.source_info) as TenCloudSourceInfo;
        const domain = props.data.extraInfo as string;
        const res = await listRecord(sourceInfo.secretId, sourceInfo.secretKey, domain);
        setRecordList(res.Response.RecordList);
    };

    const columns: ColumnsType<DnsRecord> = [
        {
            title: "名称",
            dataIndex: "Name",
        },
        {
            title: "值",
            dataIndex: "Value",
        },
        {
            title: "类型",
            dataIndex: "Type",
        },
        {
            title: "Ttl",
            dataIndex: "TTL",
        },
        {
            title: "状态",
            dataIndex: "Status",
        },
        {
            title: "其他",
            render: (_, row: DnsRecord) => (
                <>
                    {row.Type == "MX" && `MX:${row.MX}`}
                    {row.Type == "NS" && `DefaultNx:${row.DefaultNS}`}
                </>
            ),
        }
    ];

    useEffect(() => {
        loadDataSource();
    }, []);

    useEffect(()=>{
        if(dataSource != undefined){
            loadRecordList();
        }
    },[dataSource]);

    return (
        <LocalNodeWrap title={`域名:${props.data.extraInfo}`} nodeData={props} canChangeBgColor={false}
        extraButtonList={[
            <Button type="text" icon={<ReloadOutlined />} onClick={e => {
                e.stopPropagation();
                e.preventDefault();
                loadRecordList();
            }} title='刷新' />
        ]}>
            <Table rowKey="RecordId" dataSource={recordList} columns={columns} pagination={false} scroll={{ y: props.data.height - 100 }} className="nodrag nopan nowheel"
            />
        </LocalNodeWrap>
    );
}

export default TenCloudDnsRecordListNode;

